package com.hzsai.mininotecaller.common;

import com.google.gson.Gson;
import com.hzsai.mininotecaller.util.DateTimeUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * hzsai 2020/1/17
 * usage:
 **/
@Aspect
public class HttpLog {

    private static final Logger logger = LoggerFactory.getLogger(HttpLog.class);

    private static final Gson json = new Gson();

    private ThreadLocal<Long> startTime = new ThreadLocal<>();

    /**
     * 配置切点
     */
    @Pointcut("execution(* com.hzsai.mininotecaller.controller.*.*(..))")
    public void pointCut() {}


    /**
     * 在遇到"切点"之前
     */
    @Before("pointCut()")
    public void doBefore(JoinPoint joinPoint) {

        startTime.set(System.currentTimeMillis());

        logger.debug("{} : meet HttpLog doBefore", DateTimeUtil.getDateTime());

        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // URL
        logger.debug("url: {}", request.getRequestURL());
        // Request method, GET, POST, DELETE...
        logger.debug("method: {}", request.getMethod());
        // IP
        logger.debug("IP: {}", request.getRemoteAddr() + " : " + request.getRemoteHost());
        // class method name
        logger.debug("method: {}", joinPoint.getSignature().getDeclaringTypeName()  + "." + joinPoint.getSignature().getName());
        // args
        // TODO:
        //  BUG HERE!!!部分参数情况下不能解析正常
        logger.debug("args: {}", json.toJson(joinPoint.getArgs()));
    }

    /**
     * 在遇到切点之后
     */
    @After("pointCut()")
    public void doAfter() {
        logger.debug("Request used: {}ms", System.currentTimeMillis() - startTime.get());
    }

    /**
     * 在切点返回前
     */
    @AfterReturning(pointcut = "pointCut()")
    public void afterReturning() {
        logger.debug("Request AfterReturning...");
    }
}
